import qs from './qs.js';
import axios from './axios.js';

console.log('引入axios', axios);
console.log('引入qs', qs);

const SERVER = 'https://api.huhuiyu.top';

const tokenkey = SERVER + '_tokenkey';

const tokeninfo = {
  load: () => {
    let token = localStorage.getItem(tokenkey);
    return token ? token : '';
  },
  save: (data) => {
    // 如果应答信息中存在token就保存到本地储存
    if (data && data.token) {
      localStorage.setItem(tokenkey, data.token);
    }
  },
  clear: () => {
    localStorage.removeItem(tokenkey);
  },
};

const ajax = {
  // 发起ajax请求的方法,要素:请求的地址,请求的参数,请求的方式,结果处理
  send: (url, param, method, cb) => {
    // 将请求的方式替换成大写
    method = method ? method.toUpperCase() : 'GET';
    // 完整的url
    url = SERVER + url;
    // get请求需要转换参数为查询字符串并拼接到url
    if (method === 'GET') {
      url += '?' + qs.stringify(param);
      param = '';
    }
    // 通过axios发起请求
    let promist = axios({
      url: url,
      method: method,
      data: param,
      headers: {
        // 通过头信息传递token认证信息
        Authorization: tokeninfo.load(),
      },
    });

    promist
      .then((resp) => {
        console.log('应答结果：', resp);
        // 保存token认证信息
        tokeninfo.save(resp.data);
        cb(resp.data);
      })
      .catch((err) => {
        console.log('请求出错：', err);
        cb({ success: false, message: '出bug了' });
      });
  },
  // get请求
  get: (url, param, cb) => {
    ajax.send(url, param, 'GET', cb);
  },
  // post请求
  post: (url, param, cb) => {
    ajax.send(url, param, 'POST', cb);
  },
  // delete请求
  delete: (url, param, cb) => {
    ajax.send(url, param, 'DELETE', cb);
  },
  // put请求
  put: (url, param, cb) => {
    ajax.send(url, param, 'PUT', cb);
  },
  // patch请求
  patch: (url, param, cb) => {
    ajax.send(url, param, 'PATCH', cb);
  },

};

export default ajax;
export { qs as qs, ajax as ajax, tokeninfo as tokeninfo ,SERVER as serverUrl};
